import Core from "../Core";
import { isMap } from "../utils/TypeUtils";

// save.ts
export function save(target: any, keyName: string) {
  let arr = ModeBase.classMap.get(target.constructor);
  if (arr === undefined) {
    arr = [];
    ModeBase.classMap.set(target.constructor, arr);
  }
  arr.push(keyName);
}

function isPlainObject(obj: any): boolean {
  return obj !== null && typeof obj === "object" && !Array.isArray(obj);
}

export default class ModeBase {
  start() {
    //在初始化各模型之后,再执行调用其他模型的行为
    //throw new Error("Method not implemented.");
  }
  public static classMap: Map<Function, string[]> = new Map();
  public init() {}
  public getData(): object {
    const data = {};
    const savepars = ModeBase.classMap.get(this.constructor);
    if (savepars) {
      for (const key of savepars) {
        const value = this[key];
        if (isMap(value)) {
          // 将 Map 转换为可序列化的对象
          const plainObject: Record<string, any> = {};
          value.forEach((v, k) => {
            plainObject[k] = v;
          });
          data[key] = plainObject;
        } else if (isPlainObject(value)) {
          // 浅拷贝对象
          data[key] = { ...value };
        } else {
          // 其他类型直接赋值
          data[key] = value;
        }
      }
    }
    return data;
  }
  public readData(localData: any): void {
    let name = cc.js.getClassName(this);
    this.setData(localData[name]);
  }

  public writeData(data: any): void {
    let name = cc.js.getClassName(this);
    data[name] = this.getData();
  }

  isAllDigits(str: string): boolean {
    return /^\d+$/.test(str);
  }
  public setData(data: any): void {
    if (!data) return;

    const savepars = ModeBase.classMap.get(this.constructor);
    if (!savepars) return;

    for (const key of savepars) {
      const value = data[key];

      if (value === null || value === undefined) continue;

      // 如果字段是 Map 类型且传入的是对象，则还原为 Map
      if (this[key] instanceof Map) {
        const map = new Map();
        for (const k in value) {
          map.set(k, value[k]);
        }
        this[key] = map;
      } else if (isPlainObject(value)) {
        if (isPlainObject(this[key])) {
          // 合并已有对象
          for (const k in value) {
            this[key][k] = value[k];
          }
        } else {
          // 替换整个对象
          this[key] = { ...value };
        }
      } else {
        this[key] = value;
      }
    }
  }
}
